package it.canraid.leaflet.model;

import it.canraid.leaflet.control.Kernel;

import java.util.ArrayList;

import android.graphics.Typeface;

public class WordPill {
    private static final String ID_ASCII = "W";
    private static final int N_ELEMENTS = 6;
    public String text = "";
    public float x = 0;
    public float y = 0;
    public Typeface font = Kernel.R().fontCurrent;
    public int size = Kernel.R().sizeCurrentText;
    public int color = Kernel.R().colorCurrent;

    public WordPill(String text, float x, float y) {
	this.text = text;
	this.x = x;
	this.y = y;
    }

    public WordPill(String text, float x, float y, Typeface font, int size, int color) {
	this(text, x, y);
	this.font = font;
	this.size = size;
	this.color = color;
    }

    public WordPill clone() {
	return new WordPill(text, x, y, font, size, color);
    }

    public String generateAscii() {
	String encodeText = text.replace(";", "%1%");
	encodeText = encodeText.replace("|", "%2%");
	int indexFont = 0;
	if (font == Kernel.FONT[0]) {
	    indexFont = 0;
	} else if (font == Kernel.FONT[1]) {
	    indexFont = 1;
	} else if (font == Kernel.FONT[2]) {
	    indexFont = 2;
	}
	String response = "|" + ID_ASCII + ";" + encodeText + ";" + x + ";" + y + ";" + indexFont + ";" + size + ";" + color + ";";
	return response;
    }

    public static ArrayList<WordPill> extractWords(String ascii) {
	ArrayList<WordPill> response = new ArrayList<WordPill>();
	if (ascii == null)
	    return response;

	String[] asciiDecode = ascii.split(";");
	for (int q = 0; q < asciiDecode.length; q++) {
	    if (!asciiDecode[q].equals("|" + ID_ASCII))
		continue;
	    if (q + N_ELEMENTS >= asciiDecode.length)
		break;
	    try {
		String text_ = asciiDecode[++q];
		float x_ = Float.parseFloat(asciiDecode[++q]);
		float y_ = Float.parseFloat(asciiDecode[++q]);
		int indexFont_ = Integer.parseInt(asciiDecode[++q]);
		int size_ = Integer.parseInt(asciiDecode[++q]);
		int color_ = Integer.parseInt(asciiDecode[++q]);

		String decodeText = text_.replace("%1%", ";");
		decodeText = decodeText.replace("%2%", "|");
		response.add(new WordPill(decodeText, x_, y_, Kernel.FONT[indexFont_], size_, color_));
	    } catch (NumberFormatException e) {
		e.printStackTrace();
		continue;
	    }
	}
	return response;
    }
}
